import React, {Component} from 'react';
import {WingBlank, Flex, Button, PickerView, Modal, Toast} from '@ant-design/react-native';
import {Text, View, Image, ScrollView, TextInput, TouchableOpacity, KeyboardAvoidingView, Keyboard, Platform} from 'react-native';
import {getCityList} from '~/api/basic';
import {saveCompanyApply} from '~/api/company';
import {saveBankRegister} from '~/api/bank';
import {saveAgentRegister} from '~/api/agent';
import {sendCompanyVerifyCodeForRegister, sendBankVerifyCodeForRegister, sendAgentVerifyCodeForRegister} from '~/api/user';
import {connect} from 'react-redux';
import styles from './FromStyles';

const mapGetter = (state) => {
    return {
        userinfo: state.userinfo,
    };
};

class SignForm extends Component {
    static navigationOptions = ({navigation}) => {
        let title = '';
        if (navigation.state.params && navigation.state.params.title) {
            title = navigation.state.params.title;
        }
        return {
            title: title + '入驻申请表',
        };
    };
    constructor(props) {
        super(props);
        this.state = {
            title: '',
            submitFunc: () => {},
            codeFunc: () => {},
            params: {},
            CompanyName: '',
            PuCityNID: '',
            CityName: '',
            Address: '',
            ContacName: '',
            ContacPhone: '',
            CompanyInfo: '',
            sms: '',
            visible: false,
            cityList: [],
            selectedCity: [],
            time: 60,
            btnText: '获取验证码',
            code: this.props.userinfo.identitycode,
        };
        const identity = this.props.userinfo.identity;
        switch (identity) {
            case 11:
                this.state.title = '开发商';
                this.state.submitFunc = saveCompanyApply;
                this.state.codeFunc = sendCompanyVerifyCodeForRegister;
                this.state.params = {CompanyApplyID: 0};
                break;
            case 21:
                this.state.title = '银行';
                this.state.submitFunc = saveBankRegister;
                this.state.codeFunc = sendBankVerifyCodeForRegister;
                this.state.params = {BankRegisterID: 0};
                break;
            case 31:
                this.state.title = '代理商';
                this.state.submitFunc = saveAgentRegister;
                this.state.codeFunc = sendAgentVerifyCodeForRegister;
                this.state.params = {AgentRegisterID: 0};
                break;
        }
        this.props.navigation.setParams({title: this.state.title});
        this.getCityList();
    }

    getCityList = () => {
        getCityList().then((r) => {
            if (r.code === 0) {
                this.state.cityList = r.data;
            } else {
                Toast.info('获取城市列表失败', 1);
            }
        });
    };

    onShowCity = () => {
        Keyboard.dismiss();
        let data = this.state.cityList[0];
        let value = [];
        value.push(data.value);
        data = data.children[0];
        value.push(data.value);
        data = data.children[0];
        value.push(data.value);
        this.setState({
            selectedCity: value,
            visible: true,
        });
    };

    onConfirm = () => {
        this.setCityName();
        this.onClose();
    };

    onClose = () => {
        this.setState({
            visible: false,
        });
    };

    onChange = (value) => {
        this.setState({
            selectedCity: value,
        });
    };

    setCityName = () => {
        let data = this.state.cityList;
        let cityName = [];
        this.state.selectedCity.forEach((v) => {
            let item = data.find((it) => it.value === v);
            if (cityName.indexOf(item.label) === -1) {
                cityName.push(item.label);
            }
            data = item.children;
        });
        this.setState({
            CityName: cityName.join('/'),
        });
    };

    onSubmit = () => {
        if (this.state.ContacPhone === '') {
            Toast.info('请填写联系人电话', 1);
        } else if (!/^1[3-9]\d{9}$/.test(this.state.ContacPhone)) {
            Toast.info('请输入正确电话号码', 1);
        } else if (this.state.sms === '') {
            Toast.info('请输入验证码', 1);
        } else if (this.state.CompanyName === '') {
            Toast.info('请填写' + this.state.title + '名称', 1);
        } else if (this.state.CityName === '') {
            Toast.info('请选择城市', 1);
        } else if (this.state.Address === '') {
            Toast.info('请填写地址', 1);
        } else if (this.state.ContacName === '') {
            Toast.info('请填写联系人', 1);
        } else if (this.state.CompanyInfo === '') {
            Toast.info('请填写' + this.state.title + '简介', 1);
        } else {
            const submitFunc = this.state.submitFunc;
            submitFunc({
                ...this.state.params,
                PuCityID: this.state.selectedCity[this.state.selectedCity.length - 1],
                CompanyName: this.state.CompanyName,
                CityName: this.state.CityName,
                Address: this.state.Address,
                ContacName: this.state.ContacName,
                ContacPhone: this.state.ContacPhone,
                CompanyInfo: this.state.CompanyInfo,
                sms: this.state.sms,
            }).then((r) => {
                if (r.code === 0) {
                    Toast.info('您的入驻申请已提交，请等待审核，审核结果将以短信通知', 3, () => {
                        this.props.navigation.goBack();
                    });
                } else {
                    Toast.info(r.msg, 1);
                }
            });
        }
    };

    disableCode = () => {
        return this.state.ContacPhone === '' || this.state.time !== 60;
    };

    onTimer = () => {
        var t = setInterval(() => {
            let time = this.state.time;
            if (time <= 0) {
                clearInterval(t);
                this.setState({
                    time: 60,
                    btnText: '获取验证码',
                });
            } else {
                this.setState({
                    time: --time,
                    btnText: time + 's',
                });
            }
        }, 1000);
    };

    onCode = () => {
        if (/^1[3-9]\d{9}$/.test(this.state.ContacPhone)) {
            const codeFunc = this.state.codeFunc;
            codeFunc({
                mobile: this.state.ContacPhone,
                logincode: this.state.code,
                type: 2,
            }).then((r) => {
                if (r.code === 0) {
                    let time = this.state.time;
                    this.setState({
                        time: --time,
                        btnText: time + 's',
                    });
                    this.onTimer();
                    Toast.info('验证码已发送', 1);
                } else {
                    Toast.info(r.msg);
                }
            });
        } else {
            Toast.info('请输入正确的手机号码', 1);
        }
    };

    setCompanyName = (CompanyName) => {
        this.setState({
            CompanyName: CompanyName,
        });
    };

    setAddress = (Address) => {
        this.setState({
            Address: Address,
        });
    };

    setContacName = (ContacName) => {
        this.setState({
            ContacName: ContacName,
        });
    };

    setContacPhone = (ContacPhone) => {
        this.setState({
            ContacPhone: ContacPhone,
        });
    };

    setCompanyInfo = (CompanyInfo) => {
        this.setState({
            CompanyInfo: CompanyInfo,
        });
    };

    setPassword = (sms) => {
        this.setState({
            sms: sms,
        });
    };

    codeTextColor = () => {
        return {
            color: this.disableCode() ? 'gray' : '#E67817',
        };
    };

    renderData = () => (
        <ScrollView style={styles.body}>
            <WingBlank size="lg">
                <Text style={styles.headerTitle}>入驻申请表</Text>
                <Flex direction="column">
                    <Flex style={styles.formList} direction="column" align="start">
                        <Flex>
                            <Text style={styles.itemRequired}>*</Text>
                            <Text style={styles.itemTitle}>{this.state.title}名称</Text>
                        </Flex>
                        <TextInput
                            style={styles.itemInput}
                            placeholder={'请输入' + this.state.title + '名称'}
                            placeholderTextColor="gray"
                            onChangeText={this.setCompanyName}
                        />
                    </Flex>
                    <Flex style={styles.formList} direction="column" align="start">
                        <Flex>
                            <Text style={styles.itemRequired}>*</Text>
                            <Text style={styles.itemTitle}>选择城市</Text>
                        </Flex>
                        <Flex justify="between" onPress={this.onShowCity}>
                            {this.state.CityName === '' ? (
                                <TextInput
                                    style={styles.itemInput}
                                    editable={false}
                                    placeholder="请选择城市"
                                    placeholderTextColor="gray"
                                    onTouchStart={this.onShowCity}
                                />
                            ) : (
                                <Text style={{...styles.itemInput, lineHeight: 40}}>{this.state.CityName}</Text>
                            )}
                            <Image style={styles.moreIcon} source={require('~/assets/info/more.png')} />
                        </Flex>
                        <Modal popup={true} visible={this.state.visible} animationType="slide-up">
                            <View style={styles.cityModal}>
                                <PickerView data={this.state.cityList} value={this.state.selectedCity} onChange={this.onChange} />
                            </View>
                            <Flex justify="between">
                                <Button type="warning" style={styles.modalBtn} onPress={this.onConfirm}>
                                    确定
                                </Button>
                                <Button type="primary" style={{...styles.modalBtn, ...styles.cancelBtn}} onPress={this.onClose}>
                                    取消
                                </Button>
                            </Flex>
                        </Modal>
                    </Flex>
                    <Flex style={styles.formList} direction="column" align="start">
                        <Flex>
                            <Text style={styles.itemRequired}>*</Text>
                            <Text style={styles.itemTitle}>详细地址</Text>
                        </Flex>
                        <TextInput style={styles.itemInput} placeholderTextColor="gray" placeholder="请输入详细地址" onChangeText={this.setAddress} />
                    </Flex>
                    <Flex style={styles.formList} direction="column" align="start">
                        <Flex>
                            <Text style={styles.itemRequired}>*</Text>
                            <Text style={styles.itemTitle}>联系人</Text>
                        </Flex>
                        <TextInput
                            style={styles.itemInput}
                            placeholderTextColor="gray"
                            placeholder="请输入联系人"
                            onChangeText={this.setContacName}
                        />
                    </Flex>
                    <Flex style={styles.formList} direction="column" align="start">
                        <Flex>
                            <Text style={styles.itemRequired}>*</Text>
                            <Text style={styles.itemTitle}>{this.state.title}简介</Text>
                        </Flex>
                        <TextInput
                            style={{...styles.itemInput, ...styles.itemTextArea}}
                            multiline
                            numberOfLines={4}
                            placeholder={'请输入' + this.state.title + '简介'}
                            placeholderTextColor="gray"
                            onChangeText={this.setCompanyInfo}
                        />
                    </Flex>
                    <Flex style={styles.formList} direction="column" align="start">
                        <Flex>
                            <Text style={styles.itemRequired}>*</Text>
                            <Text style={styles.itemTitle}>联系电话</Text>
                        </Flex>
                        <TextInput
                            style={styles.itemInput}
                            maxLength={11}
                            placeholder="请输入电话号码"
                            placeholderTextColor="gray"
                            keyboardType="numeric"
                            onChangeText={this.setContacPhone}
                        />
                    </Flex>
                    <Flex style={styles.formList} direction="column" align="start">
                        <Flex>
                            <Text style={styles.itemRequired}>*</Text>
                            <Text style={styles.itemTitle}>验证码</Text>
                        </Flex>
                        <Flex>
                            <TextInput
                                style={styles.itemInput}
                                maxLength={6}
                                placeholder="请输入验证码"
                                placeholderTextColor="gray"
                                keyboardType="numeric"
                                onChangeText={this.setPassword}
                            />
                            <TouchableOpacity
                                activeOpacity={1}
                                style={styles.codeButton}
                                onPress={() => {
                                    if (!this.disableCode()) {
                                        this.onCode();
                                    }
                                }}>
                                <Text style={{...styles.codeText, ...this.codeTextColor()}}>{this.state.btnText}</Text>
                            </TouchableOpacity>
                        </Flex>
                    </Flex>
                    <Button style={{width: '80%', marginTop: 40, borderRadius: 25, marginBottom: 40}} type="warning" onPress={this.onSubmit}>
                        确认提交
                    </Button>
                </Flex>
            </WingBlank>
        </ScrollView>
    );

    render() {
        return (
            <>
                {Platform.OS === 'ios' && (
                    <KeyboardAvoidingView style={global.AppData.view_center} behavior="padding" keyboardVerticalOffset={64}>
                        {this.renderData()}
                    </KeyboardAvoidingView>
                )}
                {Platform.OS === 'android' && this.renderData()}
            </>
        );
    }
}
export default connect(mapGetter)(SignForm);
